package pages

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"github.com/yourusername/tinput/internal/core/corrector"
)

func NewInputPage(window fyne.Window) fyne.CanvasObject {
	inputEntry := widget.NewMultiLineEntry()
	inputEntry.SetPlaceHolder("Please input text to correct...")

	resultText := widget.NewRichText(
		&widget.TextSegment{
			Text: "Correction result will be displayed here...",
			Style: widget.RichTextStyle{
				ColorName: "error", //
			},
		},
	)

	resultText.Wrapping = fyne.TextWrapWord

	submitButton := widget.NewButton("Fix", func() {

		inputText := inputEntry.Text
		if inputText == "" {
			return
		}

		progress := dialog.NewProgress("fixing", "loading...", window)
		progress.Show()

		// 直接执行纠正操作（不在goroutine中）
		correctedText, suggestion, grammer, _ := corrector.Correct(inputText)

		// 更新UI
		resultText.Segments = []widget.RichTextSegment{
			&widget.TextSegment{
				Text: correctedText,
				Style: widget.RichTextStyle{
					ColorName: "error",
				},
			},
			&widget.TextSegment{
				Text: suggestion,
				Style: widget.RichTextStyle{
					ColorName: "error",
				},
			},
			&widget.TextSegment{
				Text: grammer,
				Style: widget.RichTextStyle{
					ColorName: "error",
				},
			},
		}
		resultText.Refresh()
		// diffText.Segments = []widget.RichTextSegment{
		// 	&widget.TextSegment{
		// 		Text: diff,
		// 		Style: widget.RichTextStyle{
		// 			ColorName: "error",
		// 		},
		// 	},
		// }
		// diffText.Refresh()
		progress.Hide()
	})

	// 创建布局
	content := container.NewBorder(
		inputEntry,
		container.NewVBox(submitButton),
		nil,
		nil,
		resultText,
	)

	return content
}
